package cn.com.citydo.base.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import java.util.Collection;
import java.util.Date;

/**
 * @author XuJing
 * @since 2018-05-09 10:54
 */
public class JSONUtil {

    private static SerializeConfig config = new SerializeConfig();

    static {
        config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
    }

    public static String toJSONObjectStr(Object object){
        return JSONObject.toJSONString(object,config);
    }

    public static JSONObject toJSONObject(Object object){
        return (JSONObject) JSONObject.toJSON(object,config);
    }

    public static JSONObject toJSONObjectContainDate(Object object, String dateFormat){
        SerializeConfig c = new SerializeConfig();
        c.put(Date.class, new SimpleDateFormatSerializer(dateFormat));
        return (JSONObject) JSONObject.toJSON(object,c);
    }

    public static JSONObject toJSONObject(String jsonStr){
        return JSONObject.parseObject(jsonStr);
    }

    public static String toJSONArrayStr(Object object){
        return JSONArray.toJSONString(object,config);
    }

    public static JSONArray toJSONArray(Collection collection){
        return (JSONArray) JSONArray.toJSON(collection,config);
    }

    public static JSONArray toJSONArray(String jsonStr){
        return (JSONArray) JSONArray.parse(jsonStr);
    }

    public static JSONArray toJSONArray(Collection collection, String dateFormatPattern){
        SerializeConfig c = new SerializeConfig();
        c.put(Date.class, new SimpleDateFormatSerializer(dateFormatPattern));
        return (JSONArray) JSONArray.toJSON(collection,c);
    }
}
